# -*- coding: utf-8 -*-
import json
from datetime import datetime, timedelta
import math

from scrapy.utils.project import get_project_settings

from zc_core.model.items import *
from zc_core.pipelines.helper.catalog_helper import CatalogHelper
from zc_core.util.http_util import fill_link
from zc_core.util.encrypt_util import md5
from zc_core.util.common import parse_time, parse_number


def parse_catalog(response):
    cat_list = list()
    cat_json = json.loads(response.text)
    cat1_list_js = cat_json.get('data', [])
    for cat1_js in cat1_list_js:
        cat1 = build_catalog(cat1_js, 1)
        cat_list.append(cat1)
        cat2_list_js = cat1_js.get('secondPlatformCategoryList', [])
        for cat2_js in cat2_list_js:
            cat2 = build_catalog(cat2_js, 2)
            cat_list.append(cat2)
            cat3_list_js = cat2_js.get('thirdPlatformCategoryList', [])
            for cat3_js in cat3_list_js:
                cat3 = build_catalog(cat3_js, 3)
                cat_list.append(cat3)

    return cat_list


def build_catalog(cat, level):
    entity = Catalog()
    entity['catalogId'] = str(cat.get('fcid'))
    entity['catalogName'] = cat.get('name')
    entity['parentId'] = str(cat.get('parentFCid'))
    entity['level'] = level
    if entity['level'] == 3:
        entity['leafFlag'] = 1
    else:
        entity['leafFlag'] = 0
    entity['linkable'] = 1

    return entity


def parse_supplier_count(response):
    js = json.loads(response.text)
    shop_info = js.get('data', {}).get('shopList', {})
    count = shop_info.get('count', 0)

    return count


def parse_supplier_list(response):
    suppliers = list()
    js = json.loads(response.text)
    shop_info = js.get('data', {}).get('shopList', {})
    shop_list = shop_info.get('resultList', [])
    for shop in shop_list:
        supplier = Supplier()
        supplier['id'] = shop.get('shopId')
        supplier['name'] = shop.get('shopName')
        supplier['fullName'] = shop.get('supplierName')
        supplier['skuCount'] = shop.get('shopSaleCount')
        supplier['batchNo'] = response.meta.get('batchNo')
        suppliers.append(supplier)

    return suppliers


def parse_supplier(response):
    js = json.loads(response.text)
    supplier = Supplier()
    shop = js.get('data', {})
    supplier['id'] = str(shop.get('shopId'))
    supplier['code'] = shop.get('tiezongCode')
    supplier['name'] = shop.get('organizeName')
    supplier['fullName'] = shop.get('shopName')
    supplier['mobile'] = shop.get('mobile', '')
    supplier['hotline'] = shop.get('landline', '')
    supplier['batchNo'] = response.meta.get('batchNo')

    return supplier


def parse_sku_list(response):
    cat_helper = CatalogHelper()
    meta = response.meta
    cat3_id = meta.get('cat_id')
    rs = json.loads(response.text)
    item_list = rs.get('data', {}).get('itemList', {})
    cnt = item_list.get('count', 0)
    if not cnt:
        cnt = 0
    size = item_list.get('pageSize', 30)
    if not size:
        size = 30
    total_pages = math.ceil(cnt / size)

    sku_list = list()
    for item in item_list.get('resultList', []):
        sp_name = item.get('shopName', '')
        item_skus = item.get('item_sku', [])
        for item_sku in item_skus:
            sku = Sku()
            sku['skuId'] = str(item_sku.get('skuId'))
            sku['spuId'] = str(item_sku.get('itemId'))
            sku['salePrice'] = item_sku.get('sellPrice')
            sku['catalog3Id'] = cat3_id
            cat_helper.fill(sku)
            sp_id = item_sku.get('shopId')
            sku['supplierId'] = str(sp_id)
            if sp_name:
                sku['supplierName'] = sp_name
            else:
                settings = get_project_settings()
                miss_sp_map = settings.get('MISS_SUPPLIER_MAP', {})
                sku['supplierName'] = miss_sp_map.get(sp_id)
            # sku['skuName'] = item_sku.get('skuName')
            # sku['skuImg'] = fill_link(item_sku.get('pictureUrl', ''), protocol='https')
            # sku['originPrice'] = item_sku.get('marketPrice')
            # sku['brandId'] = str(item_sku.get('brandId'))
            # sku['brandName'] = item_sku.get('brandNameChEn')
            # sku['brandEnName'] = item_sku.get('brandNameEn')
            # sku['brandModel'] = item_sku.get('modelCode')
            # sku['backCatId'] = str(item_sku.get('cid'))
            # sku['soldCount'] = item_sku.get('saleCount')
            # sku['srcContent'] = item_sku
            sku_list.append(sku)

    return sku_list, total_pages


def parse_item_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    item_data = json.loads(response.text)
    if not item_data:
        return None
    item_dict = dict()
    pub_vo = item_data.get('data', {}).get('itemPublishVo', {})
    sku_list = item_data.get('data', {}).get('itemSkuInfoList', [])
    if pub_vo and sku_list:
        brand_name = pub_vo.get('brandName')
        brand_en_name = pub_vo.get('brandNameEn', '')
        cat_list = pub_vo.get('frontCategoryVoList', [])
        for sku in sku_list:
            item = ItemData()
            item['batchNo'] = batch_no
            item['skuId'] = str(sku.get('id'))
            item['spuId'] = str(sku.get('itemId'))
            item['skuName'] = sku.get('itemName')
            if brand_name:
                item['brandId'] = md5(brand_name)
                item['brandName'] = brand_name
                item['brandCode'] = str(pub_vo.get('brandId'))
            if brand_en_name:
                item['brandEnName'] = brand_en_name
            if cat_list and len(cat_list) >= 3:
                cat1 = cat_list[0]
                item['catalog1Id'] = str(cat1.get('fcid'))
                item['catalog1Name'] = cat1.get('fcname')
                cat2 = cat_list[1]
                item['catalog2Id'] = str(cat2.get('fcid'))
                item['catalog2Name'] = cat2.get('fcname')
                cat3 = cat_list[2]
                item['catalog3Id'] = str(cat3.get('fcid'))
                item['catalog3Name'] = cat3.get('fcname')
            sp_id = str(pub_vo.get('supplierInfoImportData', {}).get('id'))
            sp_name = pub_vo.get('supplierInfoImportData', {}).get('recommendOrg')
            item['supplierId'] = sp_id
            if sp_name:
                item['supplierName'] = sp_name
            else:
                settings = get_project_settings()
                miss_sp_map = settings.get('MISS_SUPPLIER_MAP', {})
                item['supplierName'] = miss_sp_map.get(sp_id)
            item['brandModel'] = sku.get('modelCode', '')
            bar_code = sku.get('barCode', '')
            if bar_code and len(bar_code) > 90:
                bar_code = bar_code[0:90]
            item['barCode'] = bar_code
            item['unit'] = sku.get('skuUnit', '')
            item['backCatId'] = str(pub_vo.get('cid'))
            if pub_vo.get('modified', ''):
                item['onSaleTime'] = parse_time(pub_vo.get('modified'))
            item['genTime'] = datetime.utcnow()

            item_dict[str(sku.get('id'))] = item

    return item_dict


def parse_price(response):
    meta = response.meta
    item_dict = meta.get('itemDict')
    done_sku = list()
    miss_sku = set(item_dict.keys())
    item_data = json.loads(response.text)
    sku_list = item_data.get('data', [])
    if sku_list:
        for sku in sku_list:
            sku_id = str(sku.get('skuId'))
            item = item_dict.get(sku_id)
            if item:
                miss_sku.remove(sku_id)
                item['skuName'] = sku.get('skuName')
                # item['supplierId'] = str(sku.get('shopId'))
                # item['supplierName'] = sku.get('shopName')
                item['originPrice'] = parse_number(sku.get('marketPrice'))
                item['salePrice'] = parse_number(sku.get('sellPrice'))

                sold_count = sku.get('saleNum')
                if not sold_count:
                    sold_count = 0
                item['soldCount'] = sold_count
                imgs = sku.get('pictureUrl', [])
                if imgs:
                    item['skuImg'] = fill_link(imgs[0].get('pictureUrl', ''), protocol='https')
                done_sku.append(item)

        return done_sku, miss_sku
